/*
 *	main.cpp
 *
 *	afp.exe
 *
 *	Audio Finger Print project
 */

#define _CRT_SECURE_NO_WARNINGS

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#include "..\waveio\wave.h"
#include "..\waveio\waveio.h"
#include "..\sglib\spectrogram.h"

#define FRAME_N	128
float rms_treshold = 0.02f;

static WAVE wave = 
{
	'FFIR', 0, 'EVAW', 
	' tmf', 16, 
	1, // AudioFormat
	1, // NumChannels
	8000, // SampleRate
	8000*1*2, // ByteRate
	1*2, // BlockAlign
	16, // BitsPerSample
	'atad', 0
};

extern "C" float RMS(__int16* buff, int N);

int main(const int argc, const char* argv[])
{
	FILE* fout;

	int j = 0;
	int sw0 = 0;
//	__int32 bufSubstring[FRAME_N];

	float rms;
	int rms_flipflop = 0;

	printf("Audio Finger Print recognition\n");

	if(argc >= 2)
	{
		rms_treshold = (float)atof(argv[1]);
		printf("RMS Treshold %f\n", rms_treshold);
	}

	if(NULL == (fout = fopen("afp_in.wav", "wb")))
	{
		perror("open file for write");
		exit(1);
	}
	if(1 != fwrite(&wave, sizeof(WAVE), 1, fout))
	{
		perror("can not write WAVE header");
		exit(1);
	}

	if(WAVEIO_NoError != WAVEIN_Open(SG_INOUT_SIZE))
	{
		printf("waveInOpen error\n");
		exit(1);
	}

	WAVEIN_Record();

	for(j = 0; j < FRAME_N;)
	{
		sw0 = WAVEIO_sw;

		while(sw0 == WAVEIO_sw)
		{
			Sleep(0);
		}

		rms = RMS((__int16*)WAVEIO_Buffer[sw0], SG_INOUT_SIZE);

		if(rms > rms_treshold)
		{
			if(!rms_flipflop)
			{
				printf("\nRMS (%6.4f) > Treshold (%6.4f)\n", rms, rms_treshold);
			}
			rms_flipflop = 1;
		}

		if(rms_flipflop)
		{
            if(SG_INOUT_SIZE != fwrite(WAVEIO_Buffer[sw0],sizeof(__int16),SG_INOUT_SIZE,fout))
            {
                printf("can not write\n");
                break;
            }

			++j;

			printf(".");
		}
	}
	printf("\n");

	WAVEIN_Stop();

 	wave.SubChunk2Size = SG_INOUT_SIZE*sizeof(__int16) * j;
	wave.ChunkSize = wave.SubChunk2Size + 36;
	fseek(fout, 0, SEEK_SET);
	fwrite(&wave, 1, sizeof(WAVE), fout);
    fclose(fout);

//    SG_ProcessFile("afp_in.wav");

//	SG_Search(bufSubstring, FRAME_N);

	return 0;
}
